package com.xc58.highreactor.seril;

import java.io.InputStream;

import com.xc58.highreactor.exception.ParseDataException;

import static com.xc58.highreactor.util.ByteUtil.getByteFormInt;
import static com.xc58.highreactor.util.ByteUtil.toInt;
public class StringSerializer implements ISerializer<String> {

	public byte[] serialize(String rawObject) throws Exception {
		byte[] data = rawObject.getBytes("utf-8");
		byte[] length = getByteFormInt(data.length);
		byte[] result = new byte[data.length + 4];
		System.arraycopy(length, 0, result, 0, 4);
		System.arraycopy(data, 0, result, 4, data.length);
		return result;
	}

	public String deserialize(InputStream input) throws Exception {
		byte[] blength = new byte[4];
		if(input.read(blength) < 4){
			throw new ParseDataException();
		}
		int length = toInt(blength);
		byte[] bdata = new byte[length];
		if(input.read(bdata) < length){
			throw new ParseDataException();
		}
		return new String(bdata,"utf-8");
	}

}
